#include "qtmqtt.h"
#include "ui_qtmqtt.h"

qtMqtt::qtMqtt(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::qtMqtt)
{
    ui->setupUi(this);
    setFixedSize(679,454);  //固定窗口大小

    client = new QMqttClient(this);

    //在ui上展示数值
    data_show();
    data_set();
}

qtMqtt::~qtMqtt()
{
    delete ui;
}

void qtMqtt::on_connect_btn_clicked()
{
    if((client->state() == QMqttClient::Disconnected) && (ui->connect_btn->text() == "连接")){   //连接
        data_set();
        data_show();

        client->setHostname(targetServer);
        client->setPort(1883);
        client->setUsername(DeviceName + "&" + ProductKey);
        client->setClientId(clientId + "|securemode=3,signmethod=" + signmethod + ",timestamp=" + timestamp + "|");
        QString code = QMessageAuthenticationCode::hash(message.toLocal8Bit(), DeviceSecret.toLocal8Bit(), QCryptographicHash::Sha1).toHex();
        ui->code_Edit->setText(code);
        client->setPassword(QMessageAuthenticationCode::hash(message.toLocal8Bit(), DeviceSecret.toLocal8Bit(), QCryptographicHash::Sha1).toHex());
        client->connectToHost();
        if(client->state() != QMqttClient::Disconnected){  //连接上了
            connect(client,&QMqttClient::messageReceived,this,&qtMqtt::topicMessageReceived);   //连接mqtt获取消息
            ui->connect_btn->setText("断开");
            //log
            ui->debug_Edit->append("已连接服务器");
        }

    }
    else{   //断开
        client->disconnectFromHost();
        client->disconnect();
        if(client->state() == QMqttClient::Disconnected){
            ui->connect_btn->setText("连接");
            //log
            ui->debug_Edit->append("已断开服务器");
        }
    }
}

void qtMqtt::topicMessageReceived(const QByteArray &message, const QMqttTopicName &topic) //mqtt获取消息
{
    QString content;
    QJsonParseError err_rpt;
    QJsonDocument root_Doc = QJsonDocument::fromJson(message,&err_rpt); //格式化为json
    if(err_rpt.error != QJsonParseError::NoError){
        ui->debug_Edit->append("json包解析错误");
    }
    else {

        if(root_Doc.isObject()){
            QJsonObject root_Obj = root_Doc.object();
            QJsonValue value =root_Obj.value("message");    //指定key的value
            if(value.isString()){
                QString str = value.toString();
                if(str == "success"){    //成功
                    ui->debug_Edit->append("接收成功");
                }
            }
        }
    }
    //content = QDateTime::currentDateTime().toString();  //获取系统现在时间
    content += QLatin1String("Received Topic:") + topic.name(); //加topic
    //content += QLatin1String("Message:") + message + QLatin1Char('\n');
    ui->debug_Edit->append(message);
}

void qtMqtt::data_set()
{
    ProductKey = ui->ProductKey_Edit->text();
    DeviceName = ui->DeviceName_Edit->text();
    DeviceSecret = ui->DeviceSecret_Edit->text();
    RegionId = ui->RegionId_Edit->text();
    clientId = ui->clientId_Edit->text();
    signmethod = ui->signmethod_Edit->text();
    timestamp = ui->timestamp_Edit->text();
    JsonNum_1 =  ui->Num1->text().toInt();
    JsonNum_2 =  ui->Num2->text().toInt();

    PubTopic = "/sys/" + ProductKey + "/" + DeviceName + "/thing/event/property/post";
    SubTopic = "/sys/" + ProductKey + "/" + DeviceName + "/thing/service/property/set";
    targetServer = ProductKey + ".iot-as-mqtt." + RegionId + ".aliyuncs.com";
    message ="clientId"+clientId+"deviceName"+DeviceName+"productKey"+ProductKey+"timestamp"+timestamp;
    allcode = QMessageAuthenticationCode::hash(message.toLocal8Bit(), DeviceSecret.toLocal8Bit(), QCryptographicHash::Sha1).toHex();
    Json_1 = ui->Json1->text();
    Json_2 = ui->Json2->text();
}

void qtMqtt::data_show()
{
    ui->DeviceName_Edit->setText(DeviceName);
    ui->ProductKey_Edit->setText(ProductKey);
    ui->DeviceSecret_Edit->setText(DeviceSecret);
    ui->RegionId_Edit->setText(RegionId);
    ui->PubTopic_Edit->setText(PubTopic);
    ui->SubTopic_Edit->setText(SubTopic);
    ui->targetServer_Edit->setText(targetServer);
    ui->clientId_Edit->setText(clientId);
    ui->signmethod_Edit->setText(signmethod);
    ui->timestamp_Edit->setText(timestamp);
    ui->message_Edit->setText(message);
    ui->code_Edit->setText(allcode);
    ui->Json1->setText(Json_1);
    ui->Json2->setText(Json_2);
    ui->Num1->setText(QString::number(JsonNum_1));
    ui->Num2->setText(QString::number(JsonNum_2));
}

void qtMqtt::on_send_btn_clicked()
{
    if((ui->Json1->text().isEmpty()) && (ui->Json2->text().isEmpty())){
        ui->debug_Edit->append("json数据空缺");
    }
    else {
        Json_1 = ui->Json1->text();
        Json_2 = ui->Json2->text();
        JsonNum_1 =  ui->Num1->text().toInt();
        JsonNum_2 =  ui->Num2->text().toInt();
        //json打包
        QJsonObject json_data;
        QJsonObject json_out;
        if((!ui->Json1->text().isEmpty()) && (!ui->Num1->text().isEmpty())){
            json_data.insert(Json_1,JsonNum_1);
        }
        if((!ui->Json2->text().isEmpty()) && (!ui->Num2->text().isEmpty())){
            json_data.insert(Json_2,JsonNum_2);
        }
        json_out.insert("params",json_data);
        QJsonDocument document;
        document.setObject(json_out);
        QByteArray byte_array = document.toJson(QJsonDocument::Compact);
        QString json_up(byte_array);

        ui->JsonEdit->setText(json_up);
        if(client->publish(PubTopic,json_up.toUtf8()) == -1){ //发布
            //log
            ui->debug_Edit->append("发布失败");
        }
        else ui->debug_Edit->append("发布成功");
    }
}

void qtMqtt::on_get_btn_clicked()
{
    if(client->state() == QMqttClient::Connected){  //确认连接后订阅
        client->subscribe(SubTopic);
        //log
        ui->debug_Edit->append("订阅成功");
    }
}

void qtMqtt::on_new_btn_clicked()
{
    data_set();
    data_show();
    //log
    ui->debug_Edit->append("更新参数成功");
}

void qtMqtt::on_clearButton_clicked()
{
    ui->debug_Edit->clear();
}
